package xyz.xcvu.ma2.module;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;
import xyz.xcvu.ma2.utils.JsonUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

@Component
@MagicModule("res")
public class MyRes {
    @Comment("返回text文本")
    public ResponseEntity txt(@Comment("返回纯文本内容")String str) {
        return ResponseEntity.ok().header("content-type", "text/plain;charset=utf-8").body(str);
    }

    @Comment("返回html为网页")
    public ResponseEntity html(@Comment("返回html")String str) {
        return ResponseEntity.ok().header("content-type", "text/html;charset=utf-8").body(str);
    }

    @Comment("返回js脚本文件")
    public ResponseEntity js(@Comment("返回js")String str) {
        return ResponseEntity.ok().header("content-type", "application/javascript;charset=utf-8").body(str);
    }
    @Comment("返回js脚本文件")
    public ResponseEntity json(@Comment("返回js")Object obj) {
        return ResponseEntity.ok().header("content-type", "application/json;charset=utf-8").body(JsonUtils.toJson(obj));
    }

    @Comment("返回css样式文件")
    public ResponseEntity css(@Comment("返回css")String str) {
        return ResponseEntity.ok().header("content-type", "text/css;charset=utf-8").body(str);
    }

    @Comment("返回xml文件")
    public ResponseEntity xml(@Comment("返回xml")String str) {
        return ResponseEntity.ok().header("content-type", "text/xml;charset=utf-8").body(str);
    }

    @Comment("返回image文件")
    public ResponseEntity image(@Comment("文件路径") String path) throws IOException {
        BufferedImage bufferedImage = null;
        bufferedImage = ImageIO.read(new FileInputStream(path));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", out);
        return ResponseEntity.ok().header("content-type", MediaType.IMAGE_PNG_VALUE).body(out.toByteArray());
    }
}
